package com.kpx.app.utils;

import android.content.ContentResolver;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.CannedAccessControlList;
import com.alibaba.sdk.android.oss.model.CreateBucketRequest;
import com.alibaba.sdk.android.oss.model.CreateBucketResult;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.alibaba.sdk.android.oss.model.ResumableUploadRequest;
import com.alibaba.sdk.android.oss.model.ResumableUploadResult;
import com.kpx.app.Application;
import com.kpx.app.bean.AliOSS;
import com.kpx.app.utils.encrypt.Toolkit;

import java.io.File;
import java.io.FileNotFoundException;

/**
 * 作者:Ryan
 * 描述:阿里云OSS文件上传、下载工具类
 */
public class AliyunOSSUtils {
    private static AliyunOSSUtils ossUtils;
    private boolean isInited;//是否已经初始化了OSSClient
    private OSS oss;

    private AliyunOSSUtils() {
    }

    public static AliyunOSSUtils getOssUtils() {
        if (ossUtils == null) {
            synchronized (AliyunOSSUtils.class) {
                ossUtils = new AliyunOSSUtils();
            }
        }
        return ossUtils;
    }

    /**
     * 初始化OSSClient , 在调用AliyunOSSUtils的其他类之前，这个方法至少执行一次
     */
    public void initOSSClient(final String accessKey, final String screctKey) {
        try {
            String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";

// 明文设置secret的方式建议只在测试时使用，更多鉴权模式请参考后面的`访问控制`章节
            OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKey, screctKey);
            ClientConfiguration conf = new ClientConfiguration();
            conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
            conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
            conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
            conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
            oss = new OSSClient(Application.instance.getApplicationContext(), endpoint, credentialProvider, conf);
            isInited = true;
        } catch (Exception e) {
        }
    }

    public void initAliyunOSS() {
        if (UserInfoUtils.getCachedLoginUser() != null) {
            AliOSS aliOSS = UserInfoUtils.getCachedLoginUser().getACCOUNTCONFIG();
            if (aliOSS != null) {
                AliyunOSSUtils.getOssUtils().initOSSClient(Toolkit.decode(aliOSS.getAliyunKey()), Toolkit.decode(aliOSS.getAliyunSecret()));
            }
        }
    }

    /**
     * 断点续传
     *
     * @return
     */
    public OSSAsyncTask resumableUpload(String bucketName, String objectKey, String sourceFilePath, OSSProgressCallback saveCallback, OSSCompletedCallback uplaodback) {
        String recordDirectory = Environment.getExternalStorageDirectory().getAbsolutePath() + "/upload_record/";
        File recordDir = new File(recordDirectory);
        // 要保证目录存在，如果不存在则主动创建
        if (!recordDir.exists() || !recordDir.isDirectory()) {
            recordDir.mkdirs();
        }
        // 创建断点上传请求，参数中给出断点记录文件的保存位置，需是一个文件夹的绝对路径
        ResumableUploadRequest request = new ResumableUploadRequest(bucketName, objectKey, sourceFilePath, recordDirectory);
        // 设置上传过程回调
        request.setProgressCallback(saveCallback);
        if (oss == null) {
            initAliyunOSS();
        }
        OSSAsyncTask resumableTask = null;
        if (oss != null) {
            resumableTask = oss.asyncResumableUpload(request, uplaodback);
        }
// resumableTask.waitUntilFinished();
        return resumableTask;
    }

    /**
     * 上传文件到阿里云
     *
     * @param bucketName     桶名
     * @param objectKey      文件名
     * @param saveCallback   文件上传状态回调
     * @param sourceFilePath 源文件的路径
     * @return 返回TaskHandler事件调度类，可以取消、暂停和继续下载任务
     */
    public OSSAsyncTask uploadFileToOSS(String bucketName, String objectKey, String sourceFilePath, OSSProgressCallback saveCallback, OSSCompletedCallback uplaodback) throws FileNotFoundException {
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(bucketName, objectKey, sourceFilePath);
        // 异步上传时可以设置进度回调
        put.setProgressCallback(saveCallback);
        OSSAsyncTask task = null;
        if (oss == null) {
            initAliyunOSS();
        }
        if(oss!=null){
            task = oss.asyncPutObject(put, uplaodback);
        }
        // task.cancel(); // 可以取消任务
        // task.waitUntilFinished(); // 可以等待直到任务完成
        return task;
    }

    public String getAliyunImageUrl(String bucketName, String cloudKey) {
        if (StringUtil.isEmpty(bucketName) || StringUtil.isEmpty(cloudKey)) {
            return null;
        }
        return "http://www.aimianfei.com/" + bucketName + "_B_U_C_K_E_T_AND_K_E_Y_" + cloudKey;
    }

    /**
     * 根据文件路径，获取文件类型
     */
    private String getFileType(String filePath) {
        File f = new File(filePath);
        return getFileType(f);
    }

    /**
     * 根据文件获取文件类型
     */
    private String getFileType(File f) {
        if (f.exists()) {
            Uri uri = Uri.fromFile(f);
            ContentResolver cR = Application.instance.getApplicationContext().getContentResolver();
            return cR.getType(uri) == null ? "" : cR.getType(uri);
        } else {
            return "";
        }
    }
}
